package com.kerrykidz.system.util.sync;

import java.io.Serializable;

import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.lang3.SerializationUtils;

/**
 * 
 * @Desc 获取MQ的相关参数
 * @author QUINN
 * @date 2014年9月17日下午5:02:42
 */
public class ActiveMQHelper {

	/**
	 * 
	 * @Desc 获取队列名称
	 * @author QUINN
	 * @date 2014年9月16日下午6:17:19
	 * @param currentStore
	 *            当前门店简写
	 * @param targetStore
	 *            目标门店简写
	 * @return
	 */
	public static String[] getQueueName() {
		if (SyncParamHelper.ZONGBU.equals(SyncParamHelper.CURRENT_STORE))
			return SyncParamHelper.ALL_STORE;
		else
			return new String[] { SyncParamHelper.ZONGBU };
	}

	public static String[] getFileQueueName() {
		if (SyncParamHelper.ZONGBU.equals(SyncParamHelper.CURRENT_STORE))
			return SyncParamHelper.ALL_STORE_FILE_SYNC_QUEUE;
		else
			return new String[] { SyncParamHelper.ZONGBU_FILE_SYNC_QUEUE };
	}

	private static ConnectionFactory FACTORY;

	public static void initParam() {
		FACTORY = new ActiveMQConnectionFactory(SyncParamHelper.BROKER_USER, SyncParamHelper.BROKER_PWD,
				SyncParamHelper.BROKER_URL);
	}

	/**
	 * 
	 * @Desc 获取Connection,已被打开链接
	 * @author QUINN
	 * @date 2014年9月16日下午6:39:20
	 * @return
	 * @throws JMSException
	 */
	public static Connection getConnection() throws JMSException {
		Connection connection = FACTORY.createConnection();
		connection.start();
		return connection;
	}

	public static boolean push2broker(Serializable task, String queueName,int PERSISTENT) {
		try {
			Connection con = ActiveMQHelper.getConnection();
			Session session = con.createSession(true, Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue(queueName);
			MessageProducer producer = session.createProducer(destination);
			producer.setDeliveryMode(PERSISTENT);
			BytesMessage message = session.createBytesMessage();
			byte[] bys = SerializationUtils.serialize(task);
			message.writeBytes(bys);
			producer.send(message);
			session.commit();
			producer.close();
			session.close();
			con.close();
			return true;
		} catch (JMSException e) {
			e.printStackTrace();
		}
		return false;
	}

}